package com.dalongxin.work.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dalongxin.work.Constants;
import com.dalongxin.work.R;
import com.dalongxin.work.page.CloudDiskActivity;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.StatusUtils;
import com.dalongxin.work.utils.ToastUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;

import java.util.HashMap;

/**
 * Created by zhaoyu on 2017/9/7.
 * 网盘新建文件夹弹框
 */

public class CloudDiskNewFolderDialog extends Dialog {

    private String mCurrFolderId;
    private Context mContext;
    private CloudDiskActivity mFragment;
    private EditText mFolderNameEdit;
    private InputMethodManager mImm;
    private View mOkTv;

    public CloudDiskNewFolderDialog(@NonNull Context context) {
        super(context, R.style.MyDialogStyle);
    }

    public CloudDiskNewFolderDialog(@NonNull Context context, CloudDiskActivity fragment, String currFolderId) {
        super(context, R.style.MyDialogStyle);
        this.mCurrFolderId = currFolderId;
        this.mContext = context;
        this.mFragment = fragment;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_cloud_disk_create_new_folder);
        setCanceledOnTouchOutside(false);

        mImm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        mFolderNameEdit = (EditText) findViewById(R.id.folder_name_et);
        mFolderNameEdit.requestFocus();
        mFolderNameEdit.postDelayed(new Runnable() {
            @Override
            public void run() {
                mImm.showSoftInput(mFolderNameEdit, InputMethodManager.SHOW_FORCED);
            }
        }, 100);
        mFolderNameEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return event.getKeyCode() == KeyEvent.KEYCODE_ENTER; //屏蔽回车键
            }
        });

        mOkTv = findViewById(R.id.ok_tv);
        mOkTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String folderName = mFolderNameEdit.getText().toString();
                if (TextUtils.isEmpty(folderName) || folderName.trim().equals("")) {
                    Toast.makeText(mContext, "请输入文件夹名", Toast.LENGTH_SHORT).show();
                    return;
                }
                mOkTv.setEnabled(false);
                HashMap<String, String> params = new HashMap<>();
                params.put("folderName", folderName);
                params.put("parentId", mCurrFolderId);
                HttpUtil.getInstance().post(true, Constants.url_addFolder, params, new Callback.CommonCallback<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject response) {
                        LogUtil.i(response.toString());
                        if (response.optInt("ret") == 0) {
                            ToastUtil.showShort(mContext, response.optString("msg"));
                            mFragment.getCloudDiskList();
                            mFragment.getAdapter().pauseAllDownload();
                            mFragment.getAdapter().clearDownloadMap();
                            mImm.hideSoftInputFromWindow(mFolderNameEdit.getWindowToken(), 0);
                            dismiss();
                        } else {
                            StatusUtils.handleStatus(response, mContext);
                        }
                        mOkTv.setEnabled(true);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        StatusUtils.handleError(ex, mContext);
                        mOkTv.setEnabled(true);
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        });

        findViewById(R.id.cancel_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mImm.hideSoftInputFromWindow(mFolderNameEdit.getWindowToken(), 0);
                dismiss();
            }
        });

    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        if (isShowing() && shouldCloseOnTouch(getContext(),event)){
            hideKeyboard(mContext, mFolderNameEdit);
        }
        return super.onTouchEvent(event);
    }

    public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN
                && isOutOfBounds(context, event) && getWindow().peekDecorView() != null) {
            return true;
        }
        return false;
    }

    private boolean isOutOfBounds(Context context, MotionEvent event) {
        final int x = (int) event.getX();
        final int y = (int) event.getY();
        final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
        final View decorView = getWindow().getDecorView();
        return (x < -slop) || (y < -slop)
                || (x > (decorView.getWidth()+slop))
                || (y > (decorView.getHeight()+slop));
    }


    // 关闭键盘
    public void hideKeyboard(Context context, EditText et) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
        }
    }

}
